package com.lifo.utils.common.mobile;

import com.lifo.utils.common.http.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author why
 * @date 2019/5/21 0021.
 */
@Slf4j
public class MobileMsgUtil {

    /**
     * 手机短信发送工具方法
     *
     * @param mobile   接收短信手机
     * @param account  发送短信的互亿账号
     * @param password 发送短信的互亿账号密码
     * @return
     */
    public static Map<String, String> sendMobileMessage(String mobile, String serviceUrl, String account, String password) {
        String content = null;
        Map<String, String> pamras = new HashMap<String, String>();
        pamras.put("account", account);
        pamras.put("password", password);
        pamras.put("mobile", mobile);
        int number = (int) ((Math.random() * 9 + 1) * 100000);
        content = "您的验证码是：" + number + "。请不要把验证码泄露给其他人。";
        log.info("======>发送短信验证码，begin");
        log.info("======>短信接收手机号：{}", mobile);
        log.info("======>短信内容begin");
        log.info(content);
        log.info("======>短信内容end");
        pamras.put("content", content);
        String result = null;
        try {
            result = HttpClientUtil.doPost(serviceUrl, pamras);
        } catch (Exception e) {
            log.error("短信发送失败，接收短信的手机号为==>{},短信内容为=={},异常信息为==>{}", mobile, content, e.getMessage());
            e.printStackTrace();
        }
        log.info("======>短信接口返回值，begin");
        log.info(result);
        log.info("======>短信接口返回值，end");
        log.info("======>发送短信验证码，end");
        //截取字符串，获取到返回的状态值
        String sbResult = result.substring(0, (result.indexOf("<code>") + 7));
        Character code = sbResult.charAt(sbResult.length() - 1);
        Map<String, String> resultMap = new HashMap<String, String>();
        //判断状态值是否成功
        if (code != '2') {
            if (result.contains("4085")) { //短信验证码超过5条
                resultMap.put("msg", "mobileMsgOut");
            } else {
                resultMap.put("msg", "error");
            }
        } else {
            resultMap.put("msg", "success");
            resultMap.put("mobile", mobile);
            resultMap.put("number", String.valueOf(number));
            resultMap.put("content", pamras.get("content"));
        }
        return resultMap;
    }
}
